package cn.itcalvin.sncoal.cth.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.itcalvin.sncoal.cth.config.CthConfig;
import cn.itcalvin.sncoal.cth.domain.InfoMine;
import cn.itcalvin.sncoal.cth.domain.InfoUser;
import cn.itcalvin.sncoal.cth.domain.RelUserSystem;
import cn.itcalvin.sncoal.cth.mapper.main.InfoMineMapper;
import cn.itcalvin.sncoal.cth.mapper.main.RelUserSystemMapper;
import cn.itcalvin.sncoal.cth.pojo.common.*;
import cn.itcalvin.sncoal.cth.pojo.req.user.*;
import cn.itcalvin.sncoal.cth.pojo.response.user.RespUserList;
import cn.itcalvin.sncoal.cth.utils.JwtUtil;
import cn.itcalvin.sncoal.cth.utils.SnowFlakeUtils;
import cn.itcalvin.vo.Message;
import cn.itcalvin.vo.MessageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.spire.ms.System.Collections.ArrayList;
import lombok.val;
import org.apache.logging.log4j.util.Base64Util;
import org.springframework.stereotype.Service;

import cn.itcalvin.sncoal.cth.mapper.main.InfoUserMapper;
import cn.itcalvin.sncoal.cth.service.InfoUserService;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.Sqls;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class InfoUserServiceImpl implements InfoUserService{

    @Resource
    private InfoUserMapper infoUserMapper;
    @Resource
    private InfoMineMapper infoMineMapper;
    @Resource
    private RelUserSystemMapper relUserSystemMapper;

    /**
     * 登录
     *
     * @param reqLogin
     * @return
     */
    @Override
    public Message<RespUserInfo> login(ReqLogin reqLogin) {
        final InfoUser infoUser = infoUserMapper.selectOneByExample(Example.builder(InfoUser.class)
                .where(Sqls.custom()
                        .andEqualTo("loginName", reqLogin.getUserName())
                        .andEqualTo("loginPassword", reqLogin.getPassword())
                        .andEqualTo("isDelete",false)
                ).build()
        );
        if(infoUser==null){
            return MessageUtil.error("用户名或密码错误！");
        }
        if(infoUser.getLoginState()!=1){
            return MessageUtil.error("用户账号被禁用！");
        }
        String belongName = null;
        if(infoUser.getBelongId()!=null){
            final InfoMine infoMine = infoMineMapper.selectByPrimaryKey(infoUser.getBelongId());
            belongName = infoMine.getMineName();
        }
        RespUserInfo respUserInfo=new RespUserInfo(infoUser.getId(),belongName,infoUser.getBelongId(),
                infoUser.getUserName(),infoUser.getRoleId(),infoUser.getIsManager(),null);
        final String sign = JwtUtil.sign(respUserInfo);
        respUserInfo.setToken(sign);
        return MessageUtil.success(respUserInfo);
    }

    /**
     * 获取用户信息
     *
     * @param id
     * @return
     */
    @Override
    public Message<RespUserInfoEx> getUserInfo(Long id) {
        final InfoUser infoUser = infoUserMapper.selectByPrimaryKey(id);
        if(infoUser==null){
            return MessageUtil.error("获取数据失败！");
        }
        final RespUserInfoEx respUserInfoEx = RespUserInfoEx.builder().id(infoUser.getId())
                .userName(infoUser.getUserName())
                .loginName(infoUser.getLoginName())
                .roleType(infoUser.getRoleId())
                .belongId(infoUser.getBelongId())
                .mineCheckPassword(null).build();
        if(respUserInfoEx.getRoleType()==4&&infoUser.getBelongId()!=null){
            final InfoMine infoMine = infoMineMapper.selectByPrimaryKey(infoUser.getBelongId());
            respUserInfoEx.setMineCheckPassword(infoMine.getMineCheckPassword());
            respUserInfoEx.setBelongName(infoMine.getMineName());
        }
        return MessageUtil.success(respUserInfoEx);
    }

    /**
     * 修改登录密码
     *
     * @param id
     * @param reqModifyLoginPwd
     * @return
     */
    @Override
    public Message<RespUserInfo> modifyLoginPwd(Long id, ReqModifyLoginPwd reqModifyLoginPwd) {
        final InfoUser infoUser = infoUserMapper.selectOneByExample(Example.builder(InfoUser.class).where(Sqls.custom()
                .andEqualTo("id", id)
                .andEqualTo("loginPassword", reqModifyLoginPwd.getOldPassword())
        ).build());
        if(infoUser==null){
            return MessageUtil.error("获取数据失败！");
        }
        infoUser.setLoginPassword(reqModifyLoginPwd.getNewPassword());
        infoUserMapper.updateByPrimaryKey(infoUser);
        return MessageUtil.success();
    }

    /**
     * 重置登录密码
     *
     * @param reqIdList
     * @return
     */
    @Override
    public Message resetLoginPassword(ReqIdList reqIdList) {
        infoUserMapper.updateLoginPassword(reqIdList.getIdList(), Base64Util.encode(CthConfig.RESETPWD));
        return MessageUtil.success("重置密码成功，新密码为:"+CthConfig.RESETPWD);
    }

    /**
     * 用户列表
     *
     * @param reqUserList
     * @return
     */
    @Override
    public Message<List<RespUserList>> list(ReqUserList reqUserList) {
        PageHelper.startPage(reqUserList.getPageIndex(),reqUserList.getPageSize());
        List<RespUserList> list= infoUserMapper.list(reqUserList);
        PageInfo<RespUserList> pageInfo=new PageInfo<>(list);
        final val relUserSystems = relUserSystemMapper.selectAll();
        val list1 = pageInfo.getList();
        list1.forEach(e->{
            if(!e.getIsManager()){
                e.setSystemIdList(relUserSystems.stream().filter(f->f.getUserId().equals(e.getId())).map(RelUserSystem::getSystemId).collect(Collectors.toList()));
            }
        });
        return MessageUtil.success(list1, pageInfo.getTotal());
    }

    /**
     * 修改登录账号状态
     *
     * @param reqUserModifyState
     * @return
     */
    @Override
    public Message modifyState(ReqUserModifyState reqUserModifyState) {
        final InfoUser infoUser = infoUserMapper.selectByPrimaryKey(reqUserModifyState.getId());
        if (infoUser == null) {
            return MessageUtil.error("获取数据失败");
        }
        if(infoUser.getIsManager()){
            return MessageUtil.error("管理员账号不能被禁用");
        }
        infoUser.setLoginState(reqUserModifyState.getLoginState());
        infoUserMapper.updateByPrimaryKey(infoUser);
        return MessageUtil.success();
    }

    /**
     * 新增用户
     *
     * @param reqUserAdd
     * @return
     */
    @Override
    public Message add(ReqUserAdd reqUserAdd) {
        //检查账号是否存在
        final int i = infoUserMapper.selectCountByExample(Example.builder(InfoUser.class).where(Sqls.custom()
                .andEqualTo("loginName", reqUserAdd.getLoginName())
                .andEqualTo("isDelete", false)
        ).build());
        if(i>0){
            return MessageUtil.error("账号已存在");
        }
        final RespUserInfo userInfo = JwtUtil.getUserInfo();
        InfoUser infoUser=new InfoUser(){{
            setId(SnowFlakeUtils.getId());
            setCreateId(userInfo.getId());
            setCreateTime(DateUtil.date());
            setIsDelete(false);
            setLoginName(reqUserAdd.getLoginName());
            setLoginPassword(Base64Util.encode(CthConfig.RESETPWD));
            setLoginState(reqUserAdd.getLoginState());
            setRoleId(reqUserAdd.getRoleId());
            setUserName(reqUserAdd.getUserName());
            setBelongId(reqUserAdd.getBelongId());
            setIsManager(userInfo.getRoleType() == 3);  //矿区添加的都是管理员账号
        }};
        infoUserMapper.insert(infoUser);
        //如果是矿井，则需要判断权限，然后添加
        if(userInfo.getRoleType()==4&&reqUserAdd.getSystemIdList()!=null){
            List<RelUserSystem> relUserSystemList =new ArrayList();
            reqUserAdd.getSystemIdList().forEach(e->{
                relUserSystemList.add(new RelUserSystem(){{
                    setCreateId(userInfo.getId());
                    setCreateTime(DateUtil.date());
                    setId(SnowFlakeUtils.getId());
                    setSystemId(e);
                    setUserId(infoUser.getId());
                }});
            });
            relUserSystemMapper.insertListAllFiled(relUserSystemList);
        }
        return MessageUtil.success("添加成功！用户默认密码："+CthConfig.RESETPWD);
    }

    /**
     * 修改用户信息
     *
     * @param reqUserModify
     * @return
     */
    @Override
    public Message modify(ReqUserModify reqUserModify) {
        //判断修改的账号是否已经存在
        final Integer nCount = infoUserMapper.selectCountByExample(Example.builder(InfoUser.class).where(Sqls.custom()
                        .andEqualTo("isDelete", false)
                        .andEqualTo("loginName",reqUserModify.getLoginName())
                        .andNotEqualTo("id",reqUserModify.getId())
                ).build()
        );
        if(nCount>0){
            return MessageUtil.error("修改的账号已经存在！");
        }
        final RespUserInfo userInfo = JwtUtil.getUserInfo();
        infoUserMapper.modify(reqUserModify,userInfo);
        //如果是矿井，则需要判断权限，然后添加
        if(userInfo.getRoleType()==4){
            relUserSystemMapper.deleteByExample(Example.builder(RelUserSystem.class).where(Sqls.custom()
                    .andEqualTo("userId",reqUserModify.getId())
            ).build());
            if(reqUserModify.getSystemIdList()!=null){
                List<RelUserSystem> relUserSystemList =new ArrayList();
                reqUserModify.getSystemIdList().forEach(e->{
                    relUserSystemList.add(new RelUserSystem(){{
                        setCreateId(userInfo.getId());
                        setCreateTime(DateUtil.date());
                        setId(SnowFlakeUtils.getId());
                        setSystemId(e);
                        setUserId(reqUserModify.getId());
                    }});
                });
                relUserSystemMapper.insertListAllFiled(relUserSystemList);
            }
        }

        return MessageUtil.success("修改成功!");
    }

    /**
     * 删除
     *
     * @param reqLong
     * @return
     */
    @Override
    public Message delete(ReqLong reqLong) {
        final RespUserInfo userInfo = JwtUtil.getUserInfo();
        final InfoUser infoUser = infoUserMapper.selectByPrimaryKey(reqLong.getId());
        if(infoUser==null){
            return  MessageUtil.error("获取数据失败");
        }
        if(infoUser.getId().equals(userInfo.getId())){
            return MessageUtil.error("不能删除自己");
        }
        if(infoUser.getIsManager()&&userInfo.getRoleType()==4){
            return MessageUtil.error("管理员账号不能被删除");
        }
        infoUser.setDeleteId(userInfo.getId());
        infoUser.setIsDelete(true);
        infoUser.setDeleteTime(DateUtil.date());
        infoUserMapper.updateByPrimaryKey(infoUser);
        return MessageUtil.success();
    }
}
